package com.stockz.equity.manager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.equity.dao.ConfigurationDao;
import com.stockz.equity.model.Configuration;

@Component
public class ConfigurationManagerImpl implements ConfigurationManager {

	@Autowired private ConfigurationDao configurationDao;
	private final Map<String,String> configurationMap = new HashMap<String,String>();
	
	@Override
	public Configuration getByKey(String key) {
		String value = configurationMap.get(key);
		if(StringUtils.hasText(value)){
			return new Configuration(key,value);
		}else{
			return configurationDao.getByKey(key);
		}
	}

	@Override
	public void persist(Configuration configuration) {
		configurationDao.persist(configuration);
		configurationMap.put(configuration.getKey(), configuration.getValue());
	}
	
	@Override
	public Object configureBean(Object bean){
		BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
		beanWrapper.setPropertyValues(new MutablePropertyValues(configurationMap),true,true);
		return bean;
	}
	
	@Override
	public void persistConfigurationBean(Object bean) {
		
	}

	//@Scheduled(cron="")
	public void refresh(){
		destroy();
		initialize();
	}
	
	@PreDestroy
	private void destroy(){
		synchronized(configurationMap){
			configurationMap.clear();
		}
	}
	
	@PostConstruct
	public void initialize(){
		synchronized(configurationMap){
			List<Configuration> configurationList = configurationDao.getAllConfiguration();
			if(configurationList != null && !configurationList.isEmpty()){
				for(Configuration configuration : configurationList){
					configurationMap.put(configuration.getKey(), configuration.getValue());
				}
				configurationList.clear();
			}
		}
	}
	
}
